<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>19.1.11. email: Examples &mdash; Python v2.6.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.6.2',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.2 documentation" href="../index.html" />
    <link rel="up" title="19.1. email — An email and MIME handling package" href="email.html" />
    <link rel="next" title="19.2. json — JSON encoder and decoder" href="json.html" />
    <link rel="prev" title="19.1.10. email: Iterators" href="email.iterators.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="json.html" title="19.2. json — JSON encoder and decoder"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="19.1.10. email: Iterators"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="netdata.html" >19. Internet Data Handling</a> &raquo;</li>
          <li><a href="email.html" accesskey="U">19.1. <tt class="docutils literal docutils literal"><span class="pre">email</span></tt> &#8212; An email and MIME handling package</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="email-examples">
<h1>19.1.11. <a title="Package supporting the parsing, manipulating, and generating email messages, including MIME documents." class="reference external" href="email.html#module-email"><tt class="xref docutils literal"><span class="pre">email</span></tt></a>: Examples<a class="headerlink" href="#email-examples" title="Permalink to this headline">¶</a></h1>
<p>Here are a few examples of how to use the <a title="Package supporting the parsing, manipulating, and generating email messages, including MIME documents." class="reference external" href="email.html#module-email"><tt class="xref docutils literal"><span class="pre">email</span></tt></a> package to read, write,
and send simple email messages, as well as more complex MIME messages.</p>
<p>First, let&#8217;s see how to create and send a simple text message:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Import smtplib for the actual sending function</span>
<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="c"># Import the email modules we&#39;ll need</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="kn">import</span> <span class="n">MIMEText</span>

<span class="c"># Open a plain text file for reading.  For this example, assume that</span>
<span class="c"># the text file contains only ASCII characters.</span>
<span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">textfile</span><span class="p">,</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
<span class="c"># Create a text/plain message</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
<span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="c"># me == the sender&#39;s email address</span>
<span class="c"># you == the recipient&#39;s email address</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;The contents of </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">textfile</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">you</span>

<span class="c"># Send the message via our own SMTP server, but don&#39;t include the</span>
<span class="c"># envelope header.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="p">[</span><span class="n">you</span><span class="p">],</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Here&#8217;s an example of how to send a MIME message containing a bunch of family
pictures that may be residing in a directory:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Import smtplib for the actual sending function</span>
<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="c"># Here are the email package modules we&#39;ll need</span>
<span class="kn">from</span> <span class="nn">email.mime.image</span> <span class="kn">import</span> <span class="n">MIMEImage</span>
<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="kn">import</span> <span class="n">MIMEMultipart</span>

<span class="n">COMMASPACE</span> <span class="o">=</span> <span class="s">&#39;, &#39;</span>

<span class="c"># Create the container (outer) email message.</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">()</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;Our family reunion&#39;</span>
<span class="c"># me == the sender&#39;s email address</span>
<span class="c"># family = the list of all recipients&#39; email addresses</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">COMMASPACE</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">family</span><span class="p">)</span>
<span class="n">msg</span><span class="o">.</span><span class="n">preamble</span> <span class="o">=</span> <span class="s">&#39;Our family reunion&#39;</span>

<span class="c"># Assume we know that the image files are all in PNG format</span>
<span class="k">for</span> <span class="nb">file</span> <span class="ow">in</span> <span class="n">pngfiles</span><span class="p">:</span>
    <span class="c"># Open the files in binary mode.  Let the MIMEImage class automatically</span>
    <span class="c"># guess the specific image type.</span>
    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="nb">file</span><span class="p">,</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
    <span class="n">img</span> <span class="o">=</span> <span class="n">MIMEImage</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
    <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">img</span><span class="p">)</span>

<span class="c"># Send the email via our own SMTP server.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="n">family</span><span class="p">,</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Here&#8217;s an example of how to send the entire contents of a directory as an email
message: <a class="footnote-reference" href="#id3" id="id1">[1]</a></p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#!/usr/bin/env python</span>

<span class="sd">&quot;&quot;&quot;Send the contents of a directory as a MIME message.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="c"># For guessing MIME type based on file name extension</span>
<span class="kn">import</span> <span class="nn">mimetypes</span>

<span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>

<span class="kn">from</span> <span class="nn">email</span> <span class="kn">import</span> <span class="n">encoders</span>
<span class="kn">from</span> <span class="nn">email.message</span> <span class="kn">import</span> <span class="n">Message</span>
<span class="kn">from</span> <span class="nn">email.mime.audio</span> <span class="kn">import</span> <span class="n">MIMEAudio</span>
<span class="kn">from</span> <span class="nn">email.mime.base</span> <span class="kn">import</span> <span class="n">MIMEBase</span>
<span class="kn">from</span> <span class="nn">email.mime.image</span> <span class="kn">import</span> <span class="n">MIMEImage</span>
<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="kn">import</span> <span class="n">MIMEMultipart</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="kn">import</span> <span class="n">MIMEText</span>

<span class="n">COMMASPACE</span> <span class="o">=</span> <span class="s">&#39;, &#39;</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s">Send the contents of a directory as a MIME message.</span>

<span class="s">Usage: %prog [options]</span>

<span class="s">Unless the -o option is given, the email is sent by forwarding to your local</span>
<span class="s">SMTP server, which then does the normal delivery process.  Your local machine</span>
<span class="s">must be running an SMTP server.</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&#39;-d&#39;</span><span class="p">,</span> <span class="s">&#39;--directory&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&quot;&quot;&quot;Mail the contents of the specified directory,</span>
<span class="s">                      otherwise use the current directory.  Only the regular</span>
<span class="s">                      files in the directory are sent, and we don&#39;t recurse to</span>
<span class="s">                      subdirectories.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&#39;-o&#39;</span><span class="p">,</span> <span class="s">&#39;--output&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&#39;FILE&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&quot;&quot;&quot;Print the composed message to FILE instead of</span>
<span class="s">                      sending the message to the SMTP server.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&#39;-s&#39;</span><span class="p">,</span> <span class="s">&#39;--sender&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&#39;SENDER&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&#39;The value of the From: header (required)&#39;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&#39;-r&#39;</span><span class="p">,</span> <span class="s">&#39;--recipient&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;append&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&#39;RECIPIENT&#39;</span><span class="p">,</span>
                      <span class="n">default</span><span class="o">=</span><span class="p">[],</span> <span class="n">dest</span><span class="o">=</span><span class="s">&#39;recipients&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&#39;A To: header value (at least one required)&#39;</span><span class="p">)</span>
    <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">sender</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>
    <span class="n">directory</span> <span class="o">=</span> <span class="n">opts</span><span class="o">.</span><span class="n">directory</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">directory</span><span class="p">:</span>
        <span class="n">directory</span> <span class="o">=</span> <span class="s">&#39;.&#39;</span>
    <span class="c"># Create the enclosing (outer) message</span>
    <span class="n">outer</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">()</span>
    <span class="n">outer</span><span class="p">[</span><span class="s">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;Contents of directory </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="n">directory</span><span class="p">)</span>
    <span class="n">outer</span><span class="p">[</span><span class="s">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">COMMASPACE</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">)</span>
    <span class="n">outer</span><span class="p">[</span><span class="s">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">opts</span><span class="o">.</span><span class="n">sender</span>
    <span class="n">outer</span><span class="o">.</span><span class="n">preamble</span> <span class="o">=</span> <span class="s">&#39;You will not see this in a MIME-aware mail reader.</span><span class="se">\n</span><span class="s">&#39;</span>

    <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">):</span>
        <span class="n">path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">directory</span><span class="p">,</span> <span class="n">filename</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
            <span class="k">continue</span>
        <span class="c"># Guess the content type based on the file&#39;s extension.  Encoding</span>
        <span class="c"># will be ignored, although we should check for simple things like</span>
        <span class="c"># gzip&#39;d or compressed files.</span>
        <span class="n">ctype</span><span class="p">,</span> <span class="n">encoding</span> <span class="o">=</span> <span class="n">mimetypes</span><span class="o">.</span><span class="n">guess_type</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">ctype</span> <span class="ow">is</span> <span class="bp">None</span> <span class="ow">or</span> <span class="n">encoding</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="c"># No guess could be made, or the file is encoded (compressed), so</span>
            <span class="c"># use a generic bag-of-bits type.</span>
            <span class="n">ctype</span> <span class="o">=</span> <span class="s">&#39;application/octet-stream&#39;</span>
        <span class="n">maintype</span><span class="p">,</span> <span class="n">subtype</span> <span class="o">=</span> <span class="n">ctype</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&#39;/&#39;</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s">&#39;text&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
            <span class="c"># Note: we should handle calculating the charset</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s">&#39;image&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEImage</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s">&#39;audio&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEAudio</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEBase</span><span class="p">(</span><span class="n">maintype</span><span class="p">,</span> <span class="n">subtype</span><span class="p">)</span>
            <span class="n">msg</span><span class="o">.</span><span class="n">set_payload</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
            <span class="c"># Encode the payload using Base64</span>
            <span class="n">encoders</span><span class="o">.</span><span class="n">encode_base64</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
        <span class="c"># Set the filename parameter</span>
        <span class="n">msg</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s">&#39;Content-Disposition&#39;</span><span class="p">,</span> <span class="s">&#39;attachment&#39;</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="n">filename</span><span class="p">)</span>
        <span class="n">outer</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
    <span class="c"># Now send or store the message</span>
    <span class="n">composed</span> <span class="o">=</span> <span class="n">outer</span><span class="o">.</span><span class="n">as_string</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">opts</span><span class="o">.</span><span class="n">output</span><span class="p">:</span>
        <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">output</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">composed</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">()</span>
        <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
        <span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">sender</span><span class="p">,</span> <span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">,</span> <span class="n">composed</span><span class="p">)</span>
        <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>


<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Here&#8217;s an example of how to unpack a MIME message like the one
above, into a directory of files:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#!/usr/bin/env python</span>

<span class="sd">&quot;&quot;&quot;Unpack a MIME message into a directory of files.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">email</span>
<span class="kn">import</span> <span class="nn">errno</span>
<span class="kn">import</span> <span class="nn">mimetypes</span>

<span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s">Unpack a MIME message into a directory of files.</span>

<span class="s">Usage: %prog [options] msgfile</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&#39;-d&#39;</span><span class="p">,</span> <span class="s">&#39;--directory&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&quot;&quot;&quot;Unpack the MIME message into the named</span>
<span class="s">                      directory, which will be created if it doesn&#39;t already</span>
<span class="s">                      exist.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">msgfile</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">1</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
        <span class="c"># Ignore directory exists error</span>
        <span class="k">if</span> <span class="n">e</span><span class="o">.</span><span class="n">errno</span> <span class="o">&lt;&gt;</span> <span class="n">errno</span><span class="o">.</span><span class="n">EEXIST</span><span class="p">:</span>
            <span class="k">raise</span>

    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">msgfile</span><span class="p">)</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_file</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
    <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="n">counter</span> <span class="o">=</span> <span class="mf">1</span>
    <span class="k">for</span> <span class="n">part</span> <span class="ow">in</span> <span class="n">msg</span><span class="o">.</span><span class="n">walk</span><span class="p">():</span>
        <span class="c"># multipart/* are just containers</span>
        <span class="k">if</span> <span class="n">part</span><span class="o">.</span><span class="n">get_content_maintype</span><span class="p">()</span> <span class="o">==</span> <span class="s">&#39;multipart&#39;</span><span class="p">:</span>
            <span class="k">continue</span>
        <span class="c"># Applications should really sanitize the given filename so that an</span>
        <span class="c"># email message can&#39;t be used to overwrite important files</span>
        <span class="n">filename</span> <span class="o">=</span> <span class="n">part</span><span class="o">.</span><span class="n">get_filename</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">filename</span><span class="p">:</span>
            <span class="n">ext</span> <span class="o">=</span> <span class="n">mimetypes</span><span class="o">.</span><span class="n">guess_extension</span><span class="p">(</span><span class="n">part</span><span class="o">.</span><span class="n">get_content_type</span><span class="p">())</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">ext</span><span class="p">:</span>
                <span class="c"># Use a generic bag-of-bits extension</span>
                <span class="n">ext</span> <span class="o">=</span> <span class="s">&#39;.bin&#39;</span>
            <span class="n">filename</span> <span class="o">=</span> <span class="s">&#39;part-</span><span class="si">%03d%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">counter</span><span class="p">,</span> <span class="n">ext</span><span class="p">)</span>
        <span class="n">counter</span> <span class="o">+=</span> <span class="mf">1</span>
        <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">,</span> <span class="n">filename</span><span class="p">),</span> <span class="s">&#39;wb&#39;</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">part</span><span class="o">.</span><span class="n">get_payload</span><span class="p">(</span><span class="n">decode</span><span class="o">=</span><span class="bp">True</span><span class="p">))</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>


<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Here&#8217;s an example of how to create an HTML message with an alternative plain
text version: <a class="footnote-reference" href="#id4" id="id2">[2]</a></p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#! /usr/bin/python</span>

<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="kn">import</span> <span class="n">MIMEMultipart</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="kn">import</span> <span class="n">MIMEText</span>

<span class="c"># me == my email address</span>
<span class="c"># you == recipient&#39;s email address</span>
<span class="n">me</span> <span class="o">=</span> <span class="s">&quot;my@email.com&quot;</span>
<span class="n">you</span> <span class="o">=</span> <span class="s">&quot;your@email.com&quot;</span>

<span class="c"># Create message container - the correct MIME type is multipart/alternative.</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">(</span><span class="s">&#39;alternative&#39;</span><span class="p">)</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&quot;Link&quot;</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">you</span>

<span class="c"># Create the body of the message (a plain-text and an HTML version).</span>
<span class="n">text</span> <span class="o">=</span> <span class="s">&quot;Hi!</span><span class="se">\n</span><span class="s">How are you?</span><span class="se">\n</span><span class="s">Here is the link you wanted:</span><span class="se">\n</span><span class="s">http://www.python.org&quot;</span>
<span class="n">html</span> <span class="o">=</span> <span class="s">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s">&lt;html&gt;</span>
<span class="s">  &lt;head&gt;&lt;/head&gt;</span>
<span class="s">  &lt;body&gt;</span>
<span class="s">    &lt;p&gt;Hi!&lt;br&gt;</span>
<span class="s">       How are you?&lt;br&gt;</span>
<span class="s">       Here is the &lt;a href=&quot;http://www.python.org&quot;&gt;link&lt;/a&gt; you wanted.</span>
<span class="s">    &lt;/p&gt;</span>
<span class="s">  &lt;/body&gt;</span>
<span class="s">&lt;/html&gt;</span>
<span class="s">&quot;&quot;&quot;</span>

<span class="c"># Record the MIME types of both parts - text/plain and text/html.</span>
<span class="n">part1</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="s">&#39;plain&#39;</span><span class="p">)</span>
<span class="n">part2</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">html</span><span class="p">,</span> <span class="s">&#39;html&#39;</span><span class="p">)</span>

<span class="c"># Attach parts into message container.</span>
<span class="c"># According to RFC 2046, the last part of a multipart message, in this case</span>
<span class="c"># the HTML message, is best and preferred.</span>
<span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">part1</span><span class="p">)</span>
<span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">part2</span><span class="p">)</span>

<span class="c"># Send the message via local SMTP server.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s">&#39;localhost&#39;</span><span class="p">)</span>
<span class="c"># sendmail function takes 3 arguments: sender&#39;s address, recipient&#39;s address</span>
<span class="c"># and message to send - here it is sent as one string.</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="n">you</span><span class="p">,</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Thanks to Matthew Dixon Cowles for the original inspiration and examples.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Contributed by Martin Matejek.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h4>Previous topic</h4>
            <p class="topless"><a href="email.iterators.html"
                                  title="previous chapter">19.1.10. <tt class="docutils literal"><span class="pre">email</span></tt>: Iterators</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="json.html"
                                  title="next chapter">19.2. <tt class="docutils literal"><span class="pre">json</span></tt> &#8212; JSON encoder and decoder</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/library/email-examples.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="json.html" title="19.2. json — JSON encoder and decoder"
             >next</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="19.1.10. email: Iterators"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="netdata.html" >19. Internet Data Handling</a> &raquo;</li>
          <li><a href="email.html" >19.1. <tt class="docutils literal docutils literal"><span class="pre">email</span></tt> &#8212; An email and MIME handling package</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 1990-2009, Python Software Foundation.
      Last updated on Apr 15, 2009.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>